const { getSquare, getTaskPage, joinTask } = require('../../../utils/task')
const {formatDateTime} = require('../../../utils/date')

Page({
  data: {
    searchText: '',
    banners: [
    ],
    hotTasks: [
    ],
    tasks: [],
    current: 1,
    size: 10,
    hasMore: true,
    loading: false,
    showImageViewer: false,
    previewImageUrl: '',
    endCountDownTimers: []
  },
  onLoad() {
    this.initSquareData();
    this.loadTasks(true);
  },
  onSearchInput(e) {
    this.setData({ searchText: e.detail.value });
  },
  onSearch() {
    const keyword = this.data.searchText.trim();
    if (!keyword) {
      wx.showToast({ title: '请输入任务名称', icon: 'none' });
      return;
    }
    wx.navigateTo({ url: `/pages/task/task-search/task-search?keyword=${encodeURIComponent(keyword)}` });
  },
  onSearchConfirm(e) {
    this.setData({ searchText: e.detail.value });
    this.onSearch();
  },
  async loadTasks(reset = false) {
    if (this.data.loading || (!this.data.hasMore && !reset)) return;
    this.setData({ loading: true });
    const current = reset ? 1 : this.data.current;
    try {
      const res = await getTaskPage(current, this.data.size);
      const newTasks = res.records || [];
      const tasks = reset ? newTasks : this.data.tasks.concat(newTasks);
      // 对任务数据进行加工处理
      tasks.forEach(task => {
        task.taskStartTimeFmt = formatDateTime(task.taskStartTime);
        task.taskEndTimeFmt = formatDateTime(task.taskEndTime);
        const now = new Date();
        const end = new Date(task.taskEndTime);
        // 只保留天数，向上取整
        const daysLeft = Math.ceil((end - now) / (1000 * 60 * 60 * 24));
        task.daysLeft = daysLeft;
      });
      this.setData({
        tasks,
        current: current + 1,
        hasMore: tasks.length < (res.total || 0),
        loading: false
      });
      this.initAllEndCountDown();
    } catch (e) {
      this.setData({ loading: false });
      wx.showToast({ title: '加载任务失败', icon: 'none' });
    }
  },
  onScrollToLower() {
    this.loadTasks();
  },
  onBannerTap(e) {
    const idx = e.currentTarget.dataset.index;
    const taskId = this.data.banners[idx].id;
    wx.navigateTo({
      url: `/pages/task/task-detail/task-detail?id=${taskId}`
    });
  },
  onHotTaskTap(e) {
    const idx = e.currentTarget.dataset.index;
    const taskId = this.data.hotTasks[idx].id;
    wx.navigateTo({
      url: `/pages/task/task-detail/task-detail?id=${taskId}`
    });
  },
  onTaskTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/task/task-detail/task-detail?id=${id}`
    });
  },
  onJoin(e) {
    const id = e.currentTarget.dataset.id;
    const idx = this.data.tasks.findIndex(t => t.id === id);
    if (idx === -1 || this.data.tasks[idx].joined) return;

    if(this.data.tasks[idx].quitMidwayFlag !== 'yes') {
      wx.showModal({
        title: '加入任务提醒',
        content: '该任务禁止中途退出，确定还要加入任务吗？',
        confirmText: '退出',
        cancelText: '取消',
        success: (res) => {
          this.submitJoinTask(idx, id);
        }
      });
    } else{
      this.submitJoinTask(idx, id);
    }
    
  },
  /**
   * 提交加入任务
   * @param {*} taskId 
   */
  submitJoinTask(idx, taskId) {
    /**
     * 加入任务
     */
    joinTask(taskId).then(() => {
      const tasks = this.data.tasks.slice();
      tasks[idx].joined = true;
      this.setData({ tasks });
      wx.showToast({ title: '已加入', icon: 'success' });
    }).catch((e) => {
      console.error("加入任务失败:", e);
      wx.showToast({ title: '加入失败', icon: 'none' });
    });
  },
  onMyTask() {
    wx.navigateTo({ url: '/pages/task/my-task/my-task' });
  },
  onCheckInCenter() {
    wx.navigateTo({ url: '/pages/task/my-check-in/my-check-in' });
  },
  async initSquareData() {
    try {
      const res = await getSquare();
      const hotTasks = res.hots || [];
      hotTasks.forEach(task => {
        task.taskNameHotShow = task.taskName.length > 6 ? task.taskName.substring(0, 6) + '...' : task.taskName;
      });
      this.setData({
        banners: res.tops || [],
        hotTasks: hotTasks
      });
    } catch (e) {
      console.error("获取广场数据失败:", e);
      wx.showToast({ title: '获取广场数据失败', icon: 'none' });
    }
  },
  onRefresh() {
    this.setData({ current: 1, tasks: [], hasMore: true }, () => {
      this.loadTasks(true);
    });
  },
  onPreviewImage(e) {
    const url = e.currentTarget.dataset.url;
    this.setData({
      showImageViewer: true,
      previewImageUrl: url
    });
  },
  onImageViewerClose() {
    this.setData({
      showImageViewer: false,
      previewImageUrl: ''
    });
  },
  cutText(text, length) {
    return text.length > length ? text.substring(0, length) + '...' : text;
  },
  onShow() {
    // 假设 this.data.tasks 已有数据
    const now = new Date();
    const tasks = this.data.tasks.map(item => {
      const end = new Date(item.taskEndTime);
      const daysLeft = Math.ceil((end - now) / (1000 * 60 * 60 * 24));
      return { ...item, daysLeft };
    });
    this.setData({ tasks });
    this.initAllEndCountDown();
  },
  initAllEndCountDown() {
    if (this.data.endCountDownTimers) {
      this.data.endCountDownTimers.forEach(timer => clearTimeout(timer));
    }
    this.data.endCountDownTimers = [];
    const tasks = this.data.tasks.map((task, idx) => {
      const endTime = new Date(task.taskEndTime).getTime();
      const now = Date.now();
      let left = Math.floor((endTime - now) / 1000);
      task.endCountDownSeconds = left > 0 ? left : 0;
      task.endCountDown = this.formatEndCountDown(task.endCountDownSeconds);
      return task;
    });
    this.setData({ tasks });
    this.updateAllEndCountDown();
  },
  updateAllEndCountDown() {
    const tasks = this.data.tasks.map(task => {
      if (task.endCountDownSeconds <= 0) {
        task.endCountDown = '已结束';
        task.endCountDownSeconds = 0;
      } else {
        task.endCountDown = this.formatEndCountDown(task.endCountDownSeconds);
        task.endCountDownSeconds--;
      }
      return task;
    });
    this.setData({ tasks });
    this.data.endCountDownTimers = this.data.endCountDownTimers || [];
    this.data.endCountDownTimers.push(setTimeout(() => this.updateAllEndCountDown(), 1000));
  },
  formatEndCountDown(left) {
    if (left <= 0) return '已结束';
    const d = Math.floor(left / 86400);
    const h = Math.floor((left % 86400) / 3600);
    const m = Math.floor((left % 3600) / 60);
    const s = left % 60;
    let str = '';
    if (d > 0) str += d + '天';
    if (h > 0 || d > 0) str += h.toString().padStart(2, '0') + '时';
    str += m.toString().padStart(2, '0') + '分';
    str += s.toString().padStart(2, '0') + '秒';
    return str;
  },
  onUnload() {
    if (this.data.endCountDownTimers) {
      this.data.endCountDownTimers.forEach(timer => clearTimeout(timer));
      this.data.endCountDownTimers = [];
    }
  }
}); 